package com.sca.order.service.impl;

import com.sca.order.dao.OrderDao;
import com.sca.order.entity.Order;
import com.sca.order.service.OrderService;
import com.sca.product.entity.CommonResult;
import com.sca.product.entity.Product;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Service
public class OrderServiceImpl implements OrderService {

    private final static String PAYMENT_URL = "http://cloud-product-service";

    @Resource
    private OrderDao dao;

    @Autowired
    private RestTemplate restTemplate;

    @GlobalTransactional
    @Override
    public int create(Order order) throws Exception {
        int n = dao.create(order);

        Product payment = new Product();
        payment.setName(order.getProductId().toString());
        payment.setTotal(order.getCount());
        restTemplate.postForObject(PAYMENT_URL+"/product/create",payment, CommonResult.class);
        if(order.getStatus() == 1) {
            throw new Exception("事务回滚");
        }
        return n;
    }

    @Override
    public Order getOrderById(Long id) {
        return dao.getOrderByid(id);
    }
}
